package com.syscom.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.syscom.common.base.BasePage;
import com.syscom.common.entity.SysCode;
import com.syscom.common.mapper.SysCodeMapper;
import com.syscom.common.utils.result.AjaxResult;
import com.syscom.common.utils.result.ResultTool;
import com.syscom.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author wjz
 * @date 2020-12-22
 */
@Slf4j
@Service
public class SysCodeService {

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private SecurityUtils securityUtils;

    public AjaxResult querySysCode(BasePage basePage, QueryWrapper queryWrapper) {
        if (basePage.getPageSize() < 0) {
            List<SysCode> all = sysCodeMapper.selectList(new QueryWrapper<SysCode>()
                    .orderByAsc("order_no,object_id")
                    .isNull("parent_id")
            );
            return ResultTool.success(all);
        } else {
            Page<SysCode> page = new Page<>(basePage.getPageNo(), basePage.getPageSize());
            page = sysCodeMapper.selectPage(page, queryWrapper);
            return ResultTool.success(page);
        }
    }

    public AjaxResult addSysCode(SysCode sysCode) {

        sysCode.setCreatedDate(new Date());
        sysCode.setCreatedBy(securityUtils.getCurrentUserId());
        return ResultTool.success(sysCodeMapper.insert(sysCode));
    }

    public AjaxResult updateSysCode(SysCode sysCode) {

        sysCode.setLastUpdateDate(new Date());
        sysCode.setLastUpdateBy(securityUtils.getCurrentUserId());
        return ResultTool.success(sysCodeMapper.updateById(sysCode));
    }

    public AjaxResult deleteSysCode(Long objectId) {

        SysCode parent = sysCodeMapper.selectOne(new QueryWrapper<SysCode>()
                .eq("object_id",objectId)
                .isNull("parent_id")
        );
        sysCodeMapper.deleteById(objectId);
        if(parent != null){

            sysCodeMapper.delete(new QueryWrapper<SysCode>().eq("parent_id",objectId));
        }
        return ResultTool.success();
    }
}

